package com.miao.common.controller;

import com.alibaba.fastjson.JSON;
import com.miao.common.entity.R;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MiaoWenqing
 * @description: 高德地图api
 * @date 2021/2/20 11:30
 */
@RestController
@RequestMapping("/common/amap")
public class AmapController {

    private final String miaoWebKey="58ec12e8aa0ff335c762df2eeff3e508";
    private final String shopApiKey="6d95b44de9c0f1c9fc7ce5f7b5c91e9f";


    @GetMapping("/map")
    public R getNavLocation(HttpServletRequest req){

        String ip = req.getRemoteAddr();
//           String ip="223.91.72.4";
         String url="https://restapi.amap.com/v3/ip?ip="+ip+"&key="+shopApiKey;

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet(url);
        Map<String, Object> resMap = new HashMap<>();


        // 响应模型
        CloseableHttpResponse response = null;
        // 由客户端执行(发送)Get请求
        try {
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            if (response != null) {
                HttpEntity responseEntity = response.getEntity();
                Map map = JSON.parseObject(EntityUtils.toString(responseEntity), Map.class);
                String province = (String) map.get("province");
                String city = (String) map.get("city");
                String rectangle = (String) map.get("rectangle");
                BigDecimal dimension = (new BigDecimal(rectangle.split(";")[0].split(",")[1]).add(new BigDecimal(rectangle.split(";")[1].split(",")[1]))).divide(new BigDecimal("2"));
                BigDecimal longitude= (new BigDecimal(rectangle.split(";")[0].split(",")[0]).add(new BigDecimal(rectangle.split(";")[1].split(",")[0]))).divide(new BigDecimal("2"));
                resMap.put("position", province+city);
                resMap.put("rectangle", longitude.toString()+","+ dimension.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return R.ok(resMap);

    }
}
